package com.hlk.emos.wx.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.hlk.emos.wx.config.shiro.JwtConfig;
import com.hlk.emos.wx.config.shiro.JwtUtil;
import com.hlk.emos.wx.dto.RegisterDto;
import com.hlk.emos.wx.service.UserService;
import com.hlk.emos.wx.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * 用户表
 *
 * @author hlk hlk@gmail.com
 * @since v1.0.0 2021-05-19
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户表")
public class UserController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtConfig jwtConfig;
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @ApiOperation("注册用户")
    public Result register(@Valid @RequestBody RegisterDto dto) {
        int id = userService.registerUser(dto);
        String token = jwtUtil.createToken(id);
        Set<String> permsSet = userService.selectUserPermissions(id);
        saveCacheToken(token, id);
        Result<Object> result = new Result<>();
        result.setData(permsSet);
        result.setToken(token);
        return result;
    }

    @PostMapping("/login/{code}")
    @ApiOperation("用户登录")
    public Result login(@PathVariable("code") String code) {
        int id = userService.login(code);
        String token = jwtUtil.createToken(id);
        Set<String> permsSet = userService.selectUserPermissions(id);
        saveCacheToken(token, id);
        Result<Object> result = new Result<>();
        result.setData(permsSet);
        result.setToken(token);
        return result;
    }


    /**
     * 保存token到缓存
     *
     * @param token
     * @param id
     */
    private void saveCacheToken(String token, int id) {
        redisTemplate.opsForValue().set(token, id, jwtConfig.getCacheExpire(), TimeUnit.DAYS);
    }

}
